package cn.yunhe.video.controller;

import cn.yunhe.video.Service.ICoinService;
import cn.yunhe.video.Service.IUserInfoService;
import cn.yunhe.video.entity.Coin;
import cn.yunhe.video.entity.UserInfo;
import cn.yunhe.video.entity.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class CoinController {
    @Autowired
    private ICoinService coinService;

    @Autowired
    private IUserInfoService userInfoService;

    @RequestMapping(value = "/addCoin")
    public void addCoin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id =  Integer.parseInt(request.getParameter("id"));
        int uid = Integer.parseInt(request.getParameter("uid"));
        int num = Integer.parseInt(request.getParameter("num"));
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(uid);
        userInfo.setCoin(num);

        Video video = new Video();
        video.setId(id);


        Coin coin = new Coin();
        coin.setVideo(video);
        coin.setUserInfo(userInfo);

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        UserInfo user = userInfoService.getUserInfoByName(userInfo);
        if(user.getCoin()>=num){
            userInfoService.updateUserInfo(userInfo);
            coinService.addCoin(coin);
            out.print("true");
        }else{
            out.print("false");
        }
    }
}
